package com.grao.waterschool.human.manager.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.util.SaResult;
import com.grao.waterschool.human.entiry.dto.CreateUserDTO;
import com.grao.waterschool.human.entiry.dto.UserInfoDTO;
import com.grao.waterschool.human.entiry.po.TSysTuser;
import com.grao.waterschool.human.manager.service.UserService;
import com.grao.waterschool.human.mapper.TSysTuserMapper;
import com.grao.waterschool.human.mapper.TWschoolUserRoleLinkMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    TSysTuserMapper tuserMapper;

    @Autowired
    TWschoolUserRoleLinkMapper tuserRoleLinkMapper;

    @Override
    @Transactional
    public SaResult createUser(CreateUserDTO tuser) {

        TSysTuser user = new TSysTuser();
        if (tuserMapper.selectUserByName(tuser.getUserName()) == null) {
            user.setId(generateRandomId());
            user.setTeacherNum(tuser.getTeacherNum());
            user.setTusername(tuser.getUserName());
            user.setTnickname(tuser.getNickName());
            user.setTemail(tuser.getEmail());
            user.setTphone(tuser.getPhone());

            String password = BCrypt.hashpw(tuser.getPwd());
            user.setTpassword(password);
            tuserRoleLinkMapper.insert(user.getTeacherNum(), 3);
            tuserMapper.insert(user);
            return SaResult.ok("创建成功");
        } else {
            return SaResult.code(400);
        }
    }

    @Override
    public List<UserInfoDTO> SelectUserList() {
        List<UserInfoDTO> tSysTusers = tuserMapper.selectUserList();
        return tSysTusers;
    }

    @Override
    public TSysTuser getuserById(String userId) {
        return tuserMapper.selectById(userId);
    }


    public static int generateRandomId() {
        Random random = new Random();
        return random.nextInt(900000) + 100000;
    }
}
